package com.example.notepad.diary

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.example.notepad.R
import java.text.SimpleDateFormat
import java.util.Date

class DiaryActivity : AppCompatActivity() {
    private var editDiary: EditText? = null
    private var btnSaveDiary: Button? = null
    private var btnViewDiary: Button? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_diary)

        // 使用 findViewById 来获取视图元素
        editDiary = findViewById(R.id.editDiary)
        btnSaveDiary = findViewById(R.id.btnSaveDiary)
        btnViewDiary = findViewById(R.id.btnViewDiary)

        // 设置保存按钮的点击事件
        btnSaveDiary?.setOnClickListener {
            val diaryText = editDiary?.text.toString()
            if (diaryText.isNotEmpty()) {
                // 保存日记到本地存储
                saveDiary(diaryText)
                // 跳转到查看日记的页面
                val intent = Intent(this, DiaryListActivity::class.java)
                startActivity(intent)
                finish() // 结束当前活动，这样返回时会回到MainActivity
            }
        }

        // 设置查看日记按钮的点击事件
        btnViewDiary?.setOnClickListener {
            // 跳转到查看日记的页面
            val intent = Intent(this, DiaryListActivity::class.java)
            startActivity(intent)
            finish() // 结束当前活动，这样返回时会回到MainActivity
        }
    }

    private fun saveDiary(diaryText: String) {
        // 获取当前时间
        val currentTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())

        // 保存日记文本和时间到SharedPreferences
        val sharedPreferences = getSharedPreferences("DiaryPrefs", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putString(currentTime, diaryText)
        editor.apply()
    }
}